// 实时疫情播报
import Util from '@/gis/Util';

const componentBase = (G as any).base.ComponentBase;
const ClusterPointMap = componentBase.extend({
    // 属性
    options: {
        map: null,
        simpleRenderMgr: null,
        popupManager: null,
        featureLocate: null,
        featureHighlight: null,
        symbolConfig: null,
        highLightId: 'compresituation_sjts', // 高亮id
        popupId: 'popup_compresituation_sjts', // 弹窗唯一标识
        popupEventName: 'popup', // 详情框事件名
        featureType: 'compresituation_layer', // 聚类点图层
        server: null, // GIS服务
    },
    // 初始化
    initialize(options: any) {
        this.currentType = null;
        componentBase.prototype.initialize.call(this, options);
    },
    //  销毁
    destroy() {
        componentBase.prototype.destroy.call(this);
    },

    load() {
        componentBase.prototype.load.call(this);
        this.map.setClusterScatter(false);
        // 图层事件监听，此处开启的是地图Map的事件监听
        // this.options.simpleRenderMgr.on('click', this._onLayerClick, this);
        // this.options.simpleRenderMgr.on('noclick', this._onMouseNoClick, this);
    },

    unload() {
        componentBase.prototype.unload.call(this);
        // 关闭图层事件监听，此处关闭的是地图Map的事件监听
        // this.options.simpleRenderMgr.off('click', this._onLayerClick, this);
        // this.options.simpleRenderMgr.on('noclick', this._onMouseNoClick, this);
        // 删除弹出框和高亮，删除图层
        this._removePointLayer();
    },
    // 关闭弹出框
    closePopup() {
        this.options.popupManager.remove(this.options.popupId);
        this._hideHighlight();
    },
    // 定位点
    fitPointLocation(x: any, y: any) {
        const geom = {
            type: 'Point',
            coordinates: [parseFloat(x), parseFloat(y)],
        };
        const pointdata: any = {
            type: 'geojson',
            geom,
        };
        this.options.featureLocate.fit(pointdata, {
            maxZoom: this.map.getZoomLevel(),
        });
    },
    // 删除点图层
    _removePointLayer() {
        // 删除点高亮和详情框
        this.closePopup();
        // 同时删除供应和需求图层
        this.options.simpleRenderMgr.remove(this.options.featureType);
    },
    /**
     * 将疫情服务|人员聚集场所的点数据添加到地图上
     * @param districtCode 数据信息，包含坐标信息
     * @param type 判断是疫情服务数据|人员聚集场所数据对应的图层名称
     */
    async _addPointByType(districtCode: any, type: any) {
        // debugger
        // 添加点数据
        this.currentType = type;
        const extent = this.map.getExtent(); // envelope对象
        const bound = extent.minx + ',' + extent.miny + ', ' + extent.maxx + ',' + extent.maxy;
        const list: any = await this.options.service.getClusterPoint(districtCode, type, bound);
        const pointArr = list.data.data.counts.length > 0 ? list.data.data.counts : list.data.data.dataList
        if (pointArr.length > 0) {
            this._addPointToMap(pointArr, type);
        }

    },
    // 获取聚类点像素聚类
    _getDistance() {
        const clusterLayer = this.options.simpleRenderMgr.getLayer(this.options.featureType);
        const envelope = clusterLayer.getExtent();
        const minxPixel = this.map.getPixelFromCoordinate([envelope.minx, envelope.maxy]);
        const maxxPixel = this.map.getPixelFromCoordinate([envelope.maxx, envelope.miny]);
        const Distance = maxxPixel[0] - minxPixel[0];
        return Distance;
    },
    // 创建聚类符号
    _addclusterSymbol(size: number, radius: number, strokecolor: any, fillcolor: any) {
        let image;
        image = new g2.sfs.SimpleMarkerSymbol({
            size: radius,
            style: 'circle',
            fillColor: fillcolor,
            borderColor: strokecolor,
            borderThickness: 3,
        });

        const style = new g2.sfs.CurrencySymbol({
            markerSymbol: image,
            textSymbol: new g2.sfs.TextSymbol({
                text: size.toString(),
                foreground: new g2.sfs.Color({ r: 255, g: 255, b: 255, a: 255 }),
                borderColor: new g2.sfs.Color({ r: 255, g: 255, b: 255, a: 255 }),
                fontFamilyName: '黑体',
                fontSize: 20,
                borderThickness: 1,
            }),
        });
        return style;
    },
    _addPointToMap(pointArr: any, type: any) {
        const self = this;
        const renderType = pointArr[0].hasOwnProperty('counts') ? 0 : 1
        const simpleRenOpt: any = {
            featureType: this.options.featureType,
            featureName: '疫情实时播报',
            list: pointArr,
            type: 1, // 使用featurelayer渲染,
            idField: 'id', // 数据唯一标识的属性
        };
        simpleRenOpt.geometryBuilder = new this.options.PointGeometryBuilder({
            geometryField: ['longitude', 'latitude'],
        });
        const pointSym: any = {
            type: 'PictureMarkerSymbol',
            options: {
                width: 34,
                height: 46,
                offsetX: 17,
                offsetY: 46,
                opacity: '1',
                rotation: '0',
            },
        };
        const SymbolBuilder = (G as any).utils.SymbolBuilder.extend({
            build: (builddata: any) => {
                // 根据数据属性控制不同的显示效果
                let markerSymbol: any = null;
                if (renderType === 1) {
                    pointSym.options.source = self.options.symbolConfig.icons['compresituation_' + type + '_icon'];
                    markerSymbol = G.utils.RenderUtil.object2Symbol(pointSym);
                } else if (renderType === 0) {
                    let newRadius = 15;
                    const size = parseInt(builddata.counts)
                    if (size >= 100) { newRadius = 18 } else if (size >= 1000) { newRadius = 23 }
                    const strokecolor = new g2.sfs.Color({ r: 200, g: 0, b: 0, a: 153 });
                    const fillcolor = new g2.sfs.Color({ r: 200, g: 0, b: 0, a: 153 });  // 0.6
                    markerSymbol = self._addclusterSymbol(builddata.counts, newRadius, strokecolor, fillcolor)
                }
                return markerSymbol;
            }
        });
        simpleRenOpt.symbolBuilder = new SymbolBuilder();
        simpleRenOpt.listeners = {
            click: (event: any) => {
                // console.log(event);
                // debugger
                const element: any = event[0].element
                const attr: any = Util.attributeSet2Object(element.attributeSet);
                const districtCode = attr.code
                if (districtCode) {
                    self._addPointByType(districtCode, type)
                } else {
                    // 清除弹窗
                    self.closePopup()
                    // 点闪烁
                    self._showHighLight([element.geometry.x, element.geometry.y], type);
                    // 添加点识别弹出框
                    self._clickTip(element, type);
                }

            },
            noclick: (event: any) => {
                self.closePopup()
            }
        }
        this.options.simpleRenderMgr.add(simpleRenOpt);
    },
    // 隐藏高亮
    _hideHighlight() {
        this.options.featureHighlight.removeHighlight(this.options.highLightId);
    },

    // 点动画闪烁
    _showHighLight(coordinate: number[], type: any) {
        this._hideHighlight();
        const symbolObj: any = {
            type: 'PictureMarkerSymbol',
            options: {
                width: 64,
                height: 70,
                offsetX: 32,
                offsetY: 65,
                opacity: 1,
                rotation: 0,
                source: this.options.symbolConfig.icons.material_0_hover_icon,
            }
        };
        symbolObj.options.source = this.options.symbolConfig.icons['compresituation_' + this.currentType + '_hover_icon'];
        const options = {
            data: {
                type: 'wkt',
                geom: 'POINT(' + coordinate[0] + ' ' + coordinate[1] + ')',
            },
            style: symbolObj,
            blink: {
                enable: false,
            },
        };
        this.options.featureHighlight.addHighlight(this.options.highLightId, options);
    },
    // 设置弹出框样式
    _setTooltipStyle(eleId: any, dataObj: any) {
        jQuery(eleId).append('<div class="GisPopup_hospital">' +
            '<div class="position">' +
            '<div class="name specialName" title=' + dataObj.name + '>' + dataObj.name + '</div>' +
            '</div>' +
            '</div>');
    },
    // 弹出对话框
    _clickTip(element: any, featureType: any, ) {
        const point: any = element.geometry.getBaryCenter();
        const self = this;
        const attrObj = Util.attributeSet2Object(element.attributeSet);
        this.options.popupManager.addSimple({
            id: this.options.popupId,
            anchor: [point.x, point.y],
            className: this.options.popupId,
        });
        const eleId = "#" + self.options.popupId;
        this._setTooltipStyle(eleId, attrObj);
    },


    // 调整视野
    _fit() {
        const layer: any = this.options.simpleRenderMgr.getLayer(this.options.featureType);
        const extent: any = G.utils.LayerUtil.getLayerExtent(layer);
        if (extent) {
            this.map.pan(extent, new Array(4).fill(200));
        }
    },
});

export default ClusterPointMap;
